﻿#region Namespaces
using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Configuration;
using System.Web.Security;
using Microsoft.SharePoint; 
#endregion

namespace FBAChangePassword.FBAChangePassword
{
    public partial class FBAChangePasswordUserControl : UserControl
    {

        #region Private Variables
        private String providerName = ConfigurationManager.AppSettings["FBAProviderName"];
        private string password = ""; 
        #endregion

        #region Events
        protected void Page_Load(object sender, EventArgs e)
        {
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            lblMsg.Text = "";
            lblPassword.Text = "";

            if (String.IsNullOrEmpty(providerName))
            {
                lblMsg.Text = "Provider key is not added in web.config file.";
                return;
            }

            if (String.IsNullOrEmpty(txtLoginName.Text.Trim()))
            {
                lblMsg.Text = "Please enter login name.";
                return;
            }


            ResetPassword();


        } 
        #endregion

        #region Methods
        /// <summary>
        /// Reset the password with temporary password.
        /// </summary>
        private void ResetPassword()
        {
            SPWeb web = SPContext.Current.Web;

            SPSecurity.RunWithElevatedPrivileges(delegate()
                 {
                     try
                     {
                         SPUser user = web.EnsureUser(txtLoginName.Text.Trim());
                         password = Membership.Providers[providerName].ResetPassword(txtLoginName.Text.Trim(), "");
                         lblPassword.Text = txtLoginName.Text.Trim() + " temporary password is " + password;
                     }

                     catch (SPException spex)
                     {
                         lblMsg.Text = spex.Message;
                     }
                     catch (Exception ex)
                     {
                         lblMsg.Text = ex.Message;
                     }

                 });



        } 
        #endregion
    }
}
